package org.itstep.stepup.dal.repositories.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.itstep.stepup.dal.entities.Project;
import org.itstep.stepup.dal.repositories.ProjectRepository;


public class ProjectRepositoryImpl implements ProjectRepository {

	private final SessionFactory sessionFactory;
	
	public ProjectRepositoryImpl(SessionFactory _sessionFactory) {
		this.sessionFactory = _sessionFactory;
	}
	
	@Override
	public Project insertProject(Project project) {
		Session session = sessionFactory.openSession();
		try {
			Transaction transaction = session.beginTransaction();
			try {
				project.setUploadedDate(new Date());
				project.setAuthorId(5);
				session.save(project);
				transaction.commit();
				return project;
			} catch (HibernateException e) {
				transaction.rollback();
				throw e;
			}
		} finally {
			session.close();
		}
	}
	
	@Override
	public List<Project> getProjects() {
		Session session = sessionFactory.openSession();
		try {
			Transaction transaction = session.beginTransaction();
			try {
				List<Project> projects = (List<Project>)session.createCriteria(Project.class).list();
				transaction.commit();
				return projects;
			} catch (HibernateException e) {
				transaction.rollback();
				throw e;
			}
		} finally {
			session.close();
		}
	}

	@Override
	public Boolean isProjectUnique(String projectName) {
		Session session = sessionFactory.openSession();
		try {
			Transaction transaction = session.beginTransaction();
			try {
				String stringQuery = "SELECT COUNT(*) from Project where Name = :pname";				
				Query query = session.createQuery(stringQuery);
				query.setParameter("pname", projectName);

				Long res = (Long)query.uniqueResult();
				
				return res > 0;
			} catch (HibernateException e) {
				transaction.rollback();
				throw e;
			}
		} finally {
			session.close();
		}
		
	}		
}
